use chrono::{Duration, Local, NaiveDate};
use rocket::FromForm;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, FromForm, Deserialize)]
pub struct Item {
    pub id: u32,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub price: f32,
    #[serde(default)]
    pub made_date: String,
    pub quantity: u32,
    #[serde(default)]
    pub location: String,
    #[serde(default)]
    pub usage: String,
    #[serde(default)]
    pub bought_from: String,
    #[serde(default)]
    pub bought_date: String,
    #[serde(default)]
    pub expired: bool, // 返回时计算
    #[serde(default)]
    pub effect_months: u16,
    #[serde(default)]
    pub brand: String, // 品牌
    #[serde(default)]
    pub log: String, // 使用记录
    #[serde(default)]
    pub barcode: String, // 条码
    #[serde(default)]
    pub picture: String, // 图片 base64
}

impl PartialEq for Item {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.made_date == other.made_date
    }
}

impl Item {
    pub fn update(&mut self) {
        let date = NaiveDate::parse_from_str(self.made_date.as_str(), "%Y-%m-%d").unwrap();
        // println!("date:{:?}, effect_months: {:?}", date, self.effect_months);
        let effect_elapse = Duration::days((self.effect_months as i64) * 30);
        let local = Local::now();
        let now_date = local.naive_local().date();
        let el = now_date.signed_duration_since(date);
        self.expired = el > effect_elapse;
    }
}

#[test]
fn item_basic() {
    let item = Item {
        id: 1,
        name: String::from("感康"),
        price: 8.5_f32,
        made_date: String::from("2021-09-23"),
        quantity: 20,
        location: String::from("家"),
        usage: String::from("感冒"),
        expired: false,
        bought_from: "医院",
        bought_date: "2021-09-03",
        effect_months: 24,
        brand: String::from("比比高"),
        log: String::from("2024.11.5用了5粒"),
    };

    item.update();
    assert_eq!(false, item.expired);
}
